package pers.xiaojun.boot.tenant.core.web;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.web.filter.OncePerRequestFilter;
import pers.xiaojun.boot.tenant.config.properties.TenantProperties;
import pers.xiaojun.boot.tenant.core.context.TenantContextHolder;
import pers.xiaojun.boot.web.core.util.WebUtils;

import java.io.IOException;

/**
 * 租户上下文过滤器
 * <p>
 * 用于获取请求头中的 租户编号，并设置在上下文中
 *
 * @author xiaojun
 * @since 2025-11-21
 */
@RequiredArgsConstructor
public class TenantContextWebFilter extends OncePerRequestFilter {

    private final TenantProperties tenantProperties;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        Long tenantId = WebUtils.getHeaderAsLong(request, tenantProperties.getTenantHeader());
        if (tenantId != null) {
            TenantContextHolder.setTenantId(tenantId);
        }
        try {
            filterChain.doFilter(request, response);
        } finally {
            // 请求结束后清理线程池中的租户Id
            TenantContextHolder.clear();
        }
    }
}
